// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package purchase_remove

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/master/shop/goods"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"strings"
)

// Logic
// 删除采购.
type Logic struct {
	goods.Logic

	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	goods       *models.Goods
	kind        kind.ArcadeAdminOperation
	kindContent string
	purchase    *models.GoodsPurchase

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.purchase != nil {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunCheck,
		o.RunCheckPurchase,
		o.RunSave,
		o.RunStatistic,
	); err != nil {
		return res.WithError(err)
	}
	// 2. 保存完成.
	o.response.Id = o.purchase.Id
	return res.With(o.response)
}

// RunCheck
// 校验商品.
func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.goods, has, err = services.NewGoodsService(sess).Dao.GetById(ctx, o.request.GoodsId); err != nil {
		err = errs.ErrDatabaseQuery
	} else if !has || o.goods.ArcadeId != o.arcade.Id || o.goods.Deleted.IsYes() {
		err = errs.ErrGoodsNotFound
	}
	return
}

// RunCheckPurchase
// 校验采购.
func (o *Logic) RunCheckPurchase(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.purchase, has, err = services.NewGoodsPurchaseService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if !has || o.goods.ArcadeId != o.arcade.Id || o.goods.Deleted.IsYes() {
		err = errs.ErrGoodsPurchaseNotFound
	}
	return
}

// RunSave
// 创建采购.
func (o *Logic) RunSave(ctx context.Context, sess *db.Session) (err error) {
	// 1. 禁止删除.
	//    指定的采购下商品未售罄.
	if o.purchase.PurchaseCount > (o.purchase.SaleCount + o.purchase.LockedCount) {
		err = errs.ErrGoodsPurchaseOutOfCountToRemove
		return
	}
	// 2. 删除采购
	if o.affects, err = services.NewGoodsPurchaseService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"deleted":    kind.DeletedYes,
		"deleted_at": db.Now(),
	}, o.purchase.Id); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// RunSaveLog
// 操作日志.
func (o *Logic) RunSaveLog() {
	var changes = []string{
		fmt.Sprintf(`商品[%s]`, o.goods.Name),
		fmt.Sprintf(`采购数量[%d]`, o.purchase.PurchaseCount),
		fmt.Sprintf(`销售数量[%d]`, o.purchase.SaleCount),
		fmt.Sprintf(`冻结数量[%d]`, o.purchase.LockedCount),
	}

	o.kind = kind.ArcadeAdminOperationShopGoodsPurchaseRemove
	o.kindContent = o.kind.ToShopGoodsPurchaseRemove(strings.Join(changes, ", "))
}

// RunStatistic
// 重建统计.
func (o *Logic) RunStatistic(ctx context.Context, sess *db.Session) (err error) {
	if o.response.Stock, err = o.UpdateGoodsStock(ctx, sess, o.arcade.Id, o.goods.Id); err == nil {
		o.RunSaveLog()
	}
	return
}
